import { parseJSONSafety } from './objectUtil';
import copy from 'copy-to-clipboard';
import moment from 'moment';
import type { MomentInput } from 'moment/moment';

/**
 * 判断是否是邮箱
 * @param email
 * @returns
 */
export const isEmail = (email: string): boolean => {
    return /^([a-zA-Z\d_-])+@([a-zA-Z\d_-])+((.[a-zA-Z\d_-]{2,3}){1,2})$/.test(email);
};

/**
 * 清除缓存
 */
export const clearCache = () => {
    localStorage.clear();
    sessionStorage.clear();
};

/**
 * 设置local缓存
 * @param cacheKey key
 * @param cacheValue value
 */
export const setLocalStorage = (cacheKey: string, cacheValue: any) => {
    localStorage.setItem(cacheKey, JSON.stringify(cacheValue));
};

/**
 * 获取local缓存
 * @param cacheKey
 * @returns
 */
export const getLocalStorage = (cacheKey: string) => {
    return parseJSONSafety(localStorage.getItem(cacheKey));
};

/**
 * 复制到剪贴板
 * @param content 需要复制的内容
 */
export const copyContent = (content: string) => {
    copy(content);
};

/**
 * 返回对象类型
 * @param data
 */
export const getDataType = (data: any): string => {
    const str = Object.prototype.toString.call(data);
    return str.slice(8, -1);
};

/**
 * 返回是否是promise
 * @param promise
 */
export const isPromise = (promise: any): boolean => {
    return Object.prototype.toString.call(promise).slice(8, -1) === 'Promise';
};

/**
 * 获取Url参数
 */
export const getUrlQueryParams = (): object => {
    const search = window.location.search, // 获取url的参数部分
        obj = {};
    if (!search) return obj;
    const params = search.split('?')[1]; // 获取参数
    const paramsArr = params.split('&');
    // 遍历数组
    for (const i of paramsArr) {
        const arr = i.split('=');
        obj[arr[0]] = arr[1]; // 设置对象key,value
    }
    return obj;
};

// 拼接getUrl参数
export const splicingParams = (url: string, params?: object) => {
    let returnUrl = url;
    if (!params) return returnUrl;

    Object.keys(params).map((item: string, index: number) => {
        if (index === 0) {
            returnUrl = `${returnUrl}?${item}=${params[item]}`;
        } else {
            returnUrl = `${returnUrl}&${item}=${params[item]}`;
        }
    });
    return returnUrl;
};

/**
 * 通过window open打开窗口关闭后重新刷新父界面
 * @param url 需要打开的地址
 * @param windowName 窗口名称
 * @param windowInformation 窗口信息
 */
export const windowCloseReload = (url: string, windowName?: string, windowInformation?: string) => {
    const windowObject = window.open(url, windowName, windowInformation);
    const loop = setInterval(function () {
        if (windowObject?.closed) {
            clearInterval(loop);
            parent.location.reload();
        }
    }, 1);
};

/**
 * 返回文件后缀名
 * @param fileName 文件全名
 */
export const getFileSuffixName = (fileName: string): string => {
    // 反转filename
    const reverseFileName = fileName.split('').reverse().join('');
    // 截取第一个.的字符串
    return reverseFileName.substring(0, reverseFileName.search(/\./)).split('').reverse().join('');
};

/**
 * 处理table删除后数据
 * @param params 初始参数
 * @param dataLength 当前页数据长度
 * @param currentPage 当前页
 * @param deleteLength 删除数据长度
 */
export const tableDeletedParams = (
    dataLength: number,
    currentPage: number = 1,
    deleteLength: number,
    params?: object,
): object => {
    if (dataLength > deleteLength) {
        return {
            ...params,
        };
    }
    return {
        ...params,
        page: currentPage > 1 ? currentPage - 1 : currentPage,
    };
};

/**
 * 根据字母排序
 * @param array 需要排序的字符串数组
 * @returns
 */
export const sortByLetter = (array: string[]): string[] => {
    array.sort((str1, str2) => {
        const sort1 = str1.toUpperCase();
        const sort2 = str2.toUpperCase();
        if (sort1 < sort2) {
            return -1;
        }
        if (sort1 > sort2) {
            return 1;
        }
        return 0;
    });
    return array;
};

/**
 * 格式化从目标时间到当前时间的时间差
 * @param time
 * @param language
 */
export const formatTimeFromNow = (time: string, language: string = 'zh-cn') => {
    moment.defineLocale(language, {
        relativeTime: {
            future: '%s内',
            past: '%s前',
            s: '几秒',
            m: '1分钟',
            mm: '%d分钟',
            h: '1小时',
            hh: '%d小时',
            d: '1天',
            dd: '%d天',
            M: '1个月',
            MM: '%d个月',
            y: '1年',
            yy: '%d年',
        },
    });
    if (moment().diff(moment(time), 'hours') > 72) {
        return time;
    } else {
        return moment(time).fromNow();
    }
};

// 日期格式化成string类型
export const dateToString = (
    time: MomentInput | any,
    pattern: string = 'YYYY-MM-DD HH:mm:ss',
): string => {
    return moment(time).format(pattern);
};

// 前端生成20位UUID
export function getUuid() {
    let timestamp = new Date().getTime();
    let perforNow =
        (typeof performance !== 'undefined' && performance.now && performance.now() * 1000) || 0;
    return 'xxxxyxxxxyxxxxyxxxxy'.replace(/[xy]/g, (c) => {
        let random = Math.random() * 16;
        if (timestamp > 0) {
            random = (timestamp + random) % 10 | 0;
            timestamp = Math.floor(timestamp / 10);
        } else {
            random = (perforNow + random) % 10 | 0;
            perforNow = Math.floor(perforNow / 10);
        }
        return `${(c === 'x' ? random : (random & 0x3) | 0x8).toString(10)}`;
    });
}
